<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2019/8/28
 * Time: 13:46
 */

namespace app\apiteacher\controller;


use think\Db;

class Apilogin extends Base
{
    /**
     * 发送验证码
     * @return \think\response\Json|void
     * phone       填写的手机号
     * type        发送场景   1 注册/更换手机号第二步   2 快捷登录/忘记密码/更换手机号第一步
     * types       有图形验证码的地方 传1
     * yzm         图形验证码
     */
    public function getPhoneCode()
    {
        $params = input('param.');
        if(trim($params['phone'], ' ') == '') {
            return json(['status' => 0, 'msg' => '请输入手机号']);
        }
        if(!preg_match("/^1[3456789]\d{9}$/", $params['phone'])) {
            return json(['status' => 0, 'msg' => '手机号格式不正确']);
        }
//        $time = $_SERVER['HTTP_REQDATE'];
//        $reqKey = $_SERVER['HTTP_REQKEY'];
//        $appId = "A6070308312682";
//        $appkey = "9AF807B0-BE12-F521-6998-6D57B0CCE8BB";
//        $myreqKey = md5($appId . 'XW' . $appkey . 'XW' . $time);
//        if($myreqKey != $reqKey){
//            return json(['status'=>1,'msg'=>'非法来源']);
//        }
        $userInfo = Db::table('up_u_user')->where('user_phone', $params['phone'])->find();
        if(!empty($userInfo) && $params['type'] == 1) { //注册||更换手机号
            if($userInfo['user_status'] == 5){
                return json(['status' => 0, 'msg' => '该手机号注册的账号已被删除']);
            }else{
                return json(['status' => 0, 'msg' => '该手机号已注册']);
            }
        }
        if(empty($userInfo) && $params['type'] == 2) { //短信快捷登录||忘记密码
            return json(['status' => 0, 'msg' => '该账号不存在']);
        }
//        if(!empty($userInfo) && $params['type'] == 3) {//第三方登录时绑定手机号
//            if($params['types'] == 1) {
//                $field = '_wx_';
//            } elseif($params['types'] == 2) {
//                $field = '_qq_';
//            } else {
//                $field = '_wb_';
//            }
//            if($userInfo["user{$field}token"]) {
//                return json(['status' => 0, 'msg' => '此号码已被绑定']);
//            }
//        }
        // 图形验证码
        if(isset($params['types']) && $params['types'] == 1){
            $yzm  = input('param.yzm');
            $yzm_data = Db::table('up_phonecode')->where('phone',$params['phone'])->find();
            if($yzm_data['yzm'] != $yzm){
                return json(['status'=>22,'msg'=>'图形验证码错误']);
            }
            if($yzm_data['yzm_status'] != 1){
                return json(['status'=>22,'msg'=>'此图形验证码已使用，请重新获取']);
            }
            Db::table('up_phonecode')->where('phone',$params['phone'])->update(['yzm_status'=>2]);
        }
        $startTime = strtotime(date('Y-m-d 00:00:00'));//当天的起始时间
        $endTime = strtotime(date('Y-m-d 23:59:59'));//当天的结束时间
        $where = [];
        $where['phone'] = $params['phone'];
        $where['time'] = ['between', [$startTime, $endTime]];
        $num = Db::table('up_phonecode')->where($where)->count('id');
        if($num >= 10) {
            return json(['status' => 0, 'msg' => '短信验证码今日已发送10次，请明天再来']);
        }
        $code = GetRandCode();//6位数验证码
        $sendres = YzxSms($code, $params['phone'], '');//发送验证码
        if($sendres['code'] != '00000') {//发送不成功
            return json(['status' => 0, 'msg' => $sendres['msg']]);
        } else {
            $data = [
                'phone' => $params['phone'],//发送的手机号
                'code' => $code,//验证码
                'time' => time(),//验证码发送的时间戳
                'date_time' => date('Y-m-d H:i:s')//日期格式
            ];
            $res = Db::table('up_phonecode')->insert($data);
            if(!$res) {
                return json(['status' => 0, 'msg' => '数据库操作失败']);
            }
            return json(['status' => 200, 'msg' => $code]);
        }
    }
    
    /**
     * 图形验证码
     */
    public function pictureyzm(){
        $phone = input('param.phone');
        header("content-type:image/png");
        $validateLength=4;
        $strToDraw="";
        $chars=[
            "0","1","2","3","4",
            "5","6","7","8","9",
            "a","b","c","d","e","f","g",
            "h","i","j","k","l","m","n",
            "o","p","q","r","s","t",
            "u","v","w","x","y","z",
            "A","B","C","D","E","F","G",
            "H","I","J","K","L","M","N",
            "O","P","Q","R","S","T",
            "U","V","W","X","Y","Z"
        ];
        $imgW=80;
        $imgH=25;
        $imgRes=imagecreate($imgW,$imgH);
        $imgColor=imagecolorallocate($imgRes,255,255,100);
        $color=imagecolorallocate($imgRes,0,0,0);
        for($i=0;$i<$validateLength;$i++){
            $rand=rand(1,35);
            $strToDraw=$strToDraw.$chars[$rand];
        }
        imagestring($imgRes,5,20,5,$strToDraw,$color);
        for($i=0;$i<100;$i++){
            imagesetpixel($imgRes,rand(0,$imgW),rand(0,$imgH),$color);
        }
        $where['phone'] = $phone;
        $res= Db::table('up_phonecode')->where($where)->find();
        if($res['id']!=''){ // 不等于空的时候
            $data['yzm'] = $strToDraw;
            $data['yzm_status'] = 1;
            
            Db::table('up_phonecode')->where($where)->update($data);
        }else{//等于空空
            $data['yzm'] = $strToDraw;
            $data['phone'] = $phone;
            Db::table('up_phonecode')->insert($data);
        }
        imagepng($imgRes);
        imagedestroy($imgRes);exit;
    }
    
    /**
     * 老师注册
     * @return \think\response\Json
     * phone    手机号
     * code     验证码
     * fpwd     第一次输入的密码
     * spwd     第二次输入的密码
     * user_invite_code   邀请码
     */
    public function register(){
        $phone = trim(input('phone'), ' ');
        $code = trim(input('code'), ' ');
        $fpwd = trim(input('fpwd'), ' '); // 第一次输入的密码
        $spwd = trim(input('spwd'), ' '); // 第二次输入的密码
        $user_invite_code = trim(input('user_invite_code'), ' '); // 邀请码
        // 必填项
        if($phone == '' || $code == '' || $fpwd == '' || $spwd == ''){
            return json(['status' => 0, 'msg' => '有未填项']);
        }
        // 手机号格式
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)) {
            return json(['status' => 0, 'msg' => '请输入正确的手机号']);
        }
        $user = Db::table('up_u_user')->where('user_phone', $phone)->find();
        if(!empty($user)){
            if($user['user_status'] == 5){
                return json(['status' => 0, 'msg' => '该手机号注册的账号已被删除']);
            }else{
                return json(['status' => 0, 'msg' => '该手机号已注册']);
            }
        }
        // 密码
        if($fpwd != $spwd){
            return json(['status' => 0, 'msg' => '两次输入的密码不一致']);
        }
        //验证验证码
        $res = Db::table('up_phonecode')
            ->where('phone', $phone)
            ->order('time desc')
            ->limit(1)
            ->find();
        if($code != $res['code']) {
            return json(['status' => 0, 'msg' => '验证码错误']);
        }
        // 10分钟超时
        $now = time();
        if($now - $res['time'] >= 1801) {
            return json(['status' => 0, 'msg' => '验证码超时']);
        }
        if($res['status'] == 1) {
            return json(['status' => 0, 'msg' => '验证码已使用']);
        }
    
        $token = md5(date('YmdHis') . rand(100000, 999999));
        $data['user_password'] = md5($fpwd);
        $data['user_phone'] = $phone;
        $data['user_time'] = date('Y-m-d H:i:s');
        $data['user_last_time'] = date('Y-m-d H:i:s');
        $data['user_token'] = $token;
        $data['user_status'] = 6; // 状态  未提交认证
        $data['user_type'] = 2; // 角色  老师
        
        // 邀请码
        if(!empty($user_invite_code)){
            $have = Db::table('up_u_user')->where('user_my_code', $user_invite_code)->find();
            if($have){
                $data['user_invite_code'] = $user_invite_code;
            }
        }
        
        $user_id = Db::name('u_user')->insertGetId($data);
        
        if($user_id){
            // 随机生成用户ID
            Db::table('up_u_user')->where('user_id', $user_id)->setField('userid', $user_id . '1000');
            //修改验证码状态
            Db::table('up_phonecode')->where('id', $res['id'])->setField('status', 1);
            //注册成功后自动登录
            $userInfo = Db::table('up_u_user')->where('user_id', $user_id)->find();
            // 设置为不是第一次登录
            if($userInfo['user_is_first'] == 1){
                Db::table('up_u_user')->where('user_id', $user_id)->setField('user_is_first', 2);
            }
            
            $rytoken = $this->rongyun($userInfo['user_id'],'who',$userInfo['user_image']);
            $userInfo['rytoken'] = $rytoken['token'];
            return json(['status' => 200, 'msg' => $userInfo]);
        }else{
            return json(['status' => 0, 'msg' => '注册失败']);
        }
    }
    
    /**
     * 登录
     * @return \think\response\Json
     * phone     手机号
     * pwd       密码
     */
    public function login(){
        $phone = trim(input('phone'), ' ');
        $pwd = trim(input('pwd'), ' ');
        // 必填项
        if($phone == '' || $pwd == ''){
            return json(['status' => 0, 'msg' => '有未填项']);
        }
    
        // 手机号格式
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)) {
            return json(['status' => 0, 'msg' => '请输入正确的手机号']);
        }
    
        $user = Db::table('up_u_user')->where('user_phone', $phone)->find();
        if(empty($user)){
            return json(['status' => 0, 'msg' => '账号不存在']);
        }
        
        $password = md5($pwd);
        if(!empty($user) && $password != $user['user_password']){
            return json(['status' => 0, 'msg' => '密码错误']);
        }
    
        if($user['user_status'] == 4) {
            return json(['status' => 0, 'msg' => '该账号已被冻结']);
        }
        if($user['user_status'] == 5) {
            return json(['status' => 0, 'msg' => '该账号已被删除，请联系管理员']);
        }
    
        if($user['user_type'] == 1){
            return json(['status' => 0, 'msg' => '该账号是学生账号，请从学生端APP登录']);
        }
        $token = $token = md5(date('YmdHis') . rand(100000, 999999));
        $data['user_last_time'] = date('Y-m-d H:i:s');
        $data['user_token'] = $token;
        $data['user_online'] = 1;
        $res = Db::table('up_u_user')->where('user_phone', $phone)->update($data);
        if($res){
            $userInfo = Db::table('up_u_user')->where('user_phone', $phone)->find();
            
            // 设置为不是第一次登录
            if($userInfo['user_is_first'] == 1){
                Db::table('up_u_user')->where('user_phone', $phone)->setField('user_is_first', 2);
            }
            $rytoken = $this->rongyun($userInfo['user_id'],'who',$userInfo['user_image']);
            $userInfo['rytoken'] = $rytoken['token'];
            return json(['status' => 200, 'msg' => $userInfo]);
        }else{
            return json(['status' => 0, 'msg' => '登录失败']);
        }
    }
    
    /**
     * 快捷登录
     * @return \think\response\Json
     * phone    手机号
     * code     验证码
     * type     调用场景    1 快捷登录   2 忘记密码第一步
     */
    public function fastLogin(){
        $phone = trim(input('phone'), ' ');
        $code = trim(input('code'), ' ');
        $type = input('type');
        // 必填项
        if($phone == '' || $code == ''){
            return json(['status' => 0, 'msg' => '有未填项']);
        }
    
        // 手机号格式
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)) {
            return json(['status' => 0, 'msg' => '请输入正确的手机号']);
        }
    
        $user = Db::table('up_u_user')->where('user_phone', $phone)->find();
        if(empty($user)){
            return json(['status' => 0, 'msg' => '账号不存在']);
        }
        if($user['user_status'] == 4) {
            return json(['status' => 0, 'msg' => '该账号已被冻结']);
        }
        if($user['user_status'] == 5) {
            return json(['status' => 0, 'msg' => '该账号已被删除，请联系管理员']);
        }
    
        //验证验证码
        $res = Db::table('up_phonecode')
            ->where('phone', $phone)
            ->order('time desc')
            ->limit(1)
            ->find();
        if($code != $res['code']) {
            return json(['status' => 0, 'msg' => '验证码错误']);
        }
        // 30分钟超时
        $now = time();
        if($now - $res['time'] >= 1801) {
            return json(['status' => 0, 'msg' => '验证码超时']);
        }
        if($res['status'] == 1) {
            return json(['status' => 0, 'msg' => '验证码已使用']);
        }
        if($type == 1){
            if($user['user_type'] == 1){
                return json(['status' => 0, 'msg' => '该账号是学生账号，请从学生端APP登录']);
            }
            $token = $token = md5(date('YmdHis') . rand(100000, 999999));
            $data['user_last_time'] = date('Y-m-d H:i:s');
            $data['user_token'] = $token;
            $data['user_online'] = 1;
            $res = Db::table('up_u_user')->where('user_phone', $phone)->update($data);
            if($res){
                $userInfo = Db::table('up_u_user')->where('user_phone', $phone)->find();
                
                // 设置为不是第一次登录
                if($userInfo['user_is_first'] == 1){
                    Db::table('up_u_user')->where('user_phone', $phone)->setField('user_is_first', 2);
                }
                $rytoken = $this->rongyun($userInfo['user_id'],'who',$userInfo['user_image']);
                $userInfo['rytoken'] = $rytoken['token'];
                return json(['status' => 200, 'msg' => $userInfo]);
            }else{
                return json(['status' => 0, 'msg' => '登录失败']);
            }
        }else{
            return json(['status' => 200, 'msg' => true]);
        }
    }
    
    /**
     * 密码
     * @return \think\response\Json
     * phone     手机号
     * fpwd      第一次输入的密码/原密码
     * spwd      第二次输入的密码/新密码
     * type      1  重置密码    2  修改密码
     */
    public function resetPassword(){
        $phone = input('phone');
        $fpwd = trim(input('fpwd'), ' ');
        $spwd = trim(input('spwd'), ' ');
        $type = input('type');
        if($fpwd == '' || $spwd == ''){
            return json(['status' => 0, 'msg' => '有未填项']);
        }
        if($type == 1){
            if($fpwd != $spwd){
                return json(['status' => 0, 'msg' => '两次输入的密码不一致']);
            }
        }else{
            $old_pwd = Db::table('up_u_user')->where('user_phone', $phone)->value('user_password');
            if(md5($fpwd) != $old_pwd){
                return json(['status' => 0, 'msg' => '原密码错误']);
            }
        }
        
        $password = md5($spwd);
        $res = Db::table('up_u_user')->where('user_phone', $phone)->update(['user_password' => $password, 'user_update_time' => date('Y-m-d H:i:s')]);
        if($res){
            return json(['status' => 200, 'msg' => '设置成功']);
        }else{
            return json(['status' => 0, 'msg' => '设置失败']);
        }
    }
}